package found

import (
	"bytes"
	"chatgpt/logq"
	"errors"
	"github.com/slclub/go-tips/json"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func request(method string, address string, data map[string]any, fn func(req *http.Request)) ([]byte, error) {

	method = strings.ToUpper(method)
	var resp *http.Response
	var err error
	switch method {
	case "GET":
		resp, err = http.Get(address)
	case "POST":
		data_code, _ := json.Marshal(data)
		//resp, err = http.Post(address, "application/json", bytes.NewBuffer(data_code))
		resp, err = _post(address, bytes.NewBuffer(data_code), fn)
	case "FORM":
		form_data := make(url.Values)
		for key, value := range data {
			form_data[string(key)] = []string{value.(string)}
		}
		resp, err = http.PostForm(address, form_data)
	}

	if err != nil {
		logq.Error("[HTTP][method:%s][url:%s][param:%s]error:", method, address, data, err.Error())
		return []byte{}, nil
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logq.Error("[HTTP][BODY][READ]%s", err.Error())
		return body, err
	}
	if resp.StatusCode != http.StatusOK {
		err = errors.New(resp.Status)
	}
	return body, err
}

func _post(url string, body io.Reader, fn func(req *http.Request)) (resp *http.Response, err error) {
	c := http.Client{}
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	fn(req)
	//req.Header.Set("Content-Type", "application/json")
	//req.Header.Set("Authorization", "Basic "+)
	return c.Do(req)
}
